import sqlite3
from tqsdk import TqApi, TqAuth, TqKq
import os

# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 构建数据库路径，向上两级目录
db_path = os.path.join(current_dir, '../../trade_monitor.db')

try:
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM products WHERE is_monitored = 1")
    products = cursor.fetchall()
    symbols = [row[2] for row in products]
    conn.close()
except Exception as e:
    print(f"从数据库获取监控品种时出错: {e}")
    symbols = []

# 初始化 TqApi
api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

try:
    # 用于存储有持仓的品种
    position_symbols = []
    for symbol in symbols:
        position = api.get_position(symbol)
        # 检查是否有持仓，多仓或空仓不为 0 则认为有持仓
        if position.pos_long > 0 or position.pos_short > 0:
            position_symbols.append(symbol)

    for symbol in position_symbols:
        quote = api.get_quote(symbol)
        # 等待行情数据更新
        #api.wait_update()
        print(f"持仓品种: {symbol} 的 quote 属性值如下:")
        # 遍历 quote 对象的属性
        for attr in dir(quote):
            # 排除内置属性和方法
            if not attr.startswith('__'):
                value = getattr(quote, attr)
                print(f"{attr}: {value}")
        print("-" * 50)  # 分隔不同品种的输出

except Exception as e:
    print(f"获取行情信息时出错: {e}")
finally:
    api.close()
